package com.bocai.dahuatech.ui.activity;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.PopBean;
import com.bocai.dahuatech.Bean.SolutionListBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.base.BaseActivity;
import com.bocai.dahuatech.utils.LoginDialogUtil;
import com.bocai.dahuatech.utils.SharePopUtil;
import com.bocai.dahuatech.utils.SharePrefencesUtil;
import com.bocai.dahuatech.utils.ShareUtil;
import com.bocai.dahuatech.utils.UrlData;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnClickListener;
import com.orhanobut.dialogplus.ViewHolder;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SolutionDetailActivity extends BaseActivity{

    SolutionListBean.ContentEntity bean;
    int type;
    @Bind(R.id.web_solution)
    WebView webSolution;
    SharePopUtil sharePopUtil;
    ShareUtil shareUtil=new ShareUtil();
    @Override
    protected int contentView()
    {
        return R.layout.activity_solution_detail;
    }

    @Override
    protected void initView()
    {
        ButterKnife.bind(this);
        initToolbar(R.string.solutiondetail);
        mToolbar.inflateMenu(R.menu.menu_share);
        bean= (SolutionListBean.ContentEntity) getIntent().getSerializableExtra("bean");
        type=getIntent().getIntExtra("type", -1);
        loadData();
        initEvent();
    }

    private void loadData() {
        final ProgressBar bar = (ProgressBar)findViewById(R.id.my_profile_tracker);
        if(SharePrefencesUtil.getFAccessFlag(this)==0){
            webSolution.loadUrl(UrlData.BASEURL+"home/SolutionInfo?id=" + bean.getId() + "&type=" + type);
        }else{

            webSolution.loadUrl(UrlData.BASEURL+"home/SolutionInfo?id=" + bean.getId() + "&type=" + type + "&userId=" + SharePrefencesUtil.getFID(this));
        }
        webSolution.getSettings().setJavaScriptEnabled(true);
        webSolution.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webSolution.getSettings().setAllowFileAccess(true);
        webSolution.getSettings().setDomStorageEnabled(true);
        webSolution.requestFocus();
        webSolution.setWebChromeClient(new WebChromeClient());
        //android 调jquery(很神奇   去掉你会后悔的)
        webSolution.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//关闭缓存
        webSolution.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);//不加上，会显示白边
        webSolution.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    bar.setVisibility(View.GONE);
                } else {
                    if (View.INVISIBLE == bar.getVisibility()) {
                        bar.setVisibility(View.VISIBLE);
                    }
                    bar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }
        });
        webSolution.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                hideLoading();
                if (url.contains("solutionproduct"))
                {
                    String[] urls = url.split("solutionproduct?");
                    String[] ids = urls[1].split("&");
                    String[] productIds = ids[0].split("=");
                    String[] solutionIds = ids[1].split("=");
                    Intent intent = new Intent(SolutionDetailActivity.this, NewProductDetailActivity.class);
                    intent.putExtra("productId", Integer.parseInt(productIds[1]));
                    intent.putExtra("solutionId", solutionIds[1]);
                    startActivity(intent);
                } else
                {
                    webSolution.loadUrl(url);
                }
                return true;
            }

        });

    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                ArrayList<PopBean> list = new ArrayList<>();
                for (int i = 0; i < 2; i++) {
                    PopBean bean = new PopBean();
                    if (i == 0) {

                        bean.setId("1");
                        bean.setName(getResources().getString(R.string.collection));
                    }
                    else if (i == 1) {
                        bean.setId("2");
                        bean.setName(getResources().getString(R.string.share));
                    }
                    list.add(bean);
                }
                sharePopUtil = SharePopUtil.getInstance(SolutionDetailActivity.this, mToolbar, 200, 100, list);
                sharePopUtil.setListener(new SharePopUtil.OnDatePopClickListener() {
                    @Override
                    public void onClick(SharePopUtil pu, PopBean date) {
                        if (date.getName().equals(getResources().getString(R.string.collection))) {
                            if (SharePrefencesUtil.getFAccessFlag(SolutionDetailActivity.this) == 0) {
                                LoginDialogUtil.loginDialog(SolutionDetailActivity.this);

                            } else {

                                ifCollected();
                            }
                            sharePopUtil.dismiss();
                        } else if (date.getName().equals(getResources().getString(R.string.share))) {
                            DialogPlus dialogPlus = DialogPlus.newDialog(SolutionDetailActivity.this)
                                    .setContentHolder(new ViewHolder(R.layout.dialog_share))
                                    .setOnClickListener(new OnClickListener() {
                                        @Override
                                        public void onClick(DialogPlus dialog, View view) {
                                            switch (view.getId()) {
                                                case R.id.ll_dialog_qq:
                                                    shareUtil.showShare(SolutionDetailActivity.this, "qq", bean.getImageUrl(),
                                                            bean.getName(), bean.getDescribe(), UrlData.BASEURL+"home/SolutionInfo?id=" + bean.getId() + "&type=" + type);
                                                    break;
                                                case R.id.ll_dialog_weixin:
                                                    shareUtil.showShare(SolutionDetailActivity.this, "weixin", bean.getImageUrl(),
                                                            bean.getName(), bean.getDescribe(), UrlData.BASEURL+"home/SolutionInfo?id=" + bean.getId() + "&type=" + type);
                                                    break;
                                                case R.id.ll_dialog_weixinfriend:
                                                    shareUtil.showShare(SolutionDetailActivity.this, "weixinfriend", bean.getImageUrl(),
                                                            bean.getName(), bean.getDescribe(), UrlData.BASEURL+"home/SolutionInfo?id=" + bean.getId() + "&type=" + type);
                                                    break;
                                                case R.id.ll_dialog_sinaweibo:
                                                    shareUtil.showShare(SolutionDetailActivity.this, "sinaweibo", bean.getImageUrl(),
                                                            bean.getName(), bean.getDescribe(), UrlData.BASEURL+"home/SolutionInfo?id=" + bean.getId() + "&type=" + type);
                                                    break;
                                                case R.id.ll_dialog_qqzone:
                                                    shareUtil.showShare(SolutionDetailActivity.this, "qqzone", bean.getImageUrl(),
                                                            bean.getName(), bean.getDescribe(), UrlData.BASEURL+"home/SolutionInfo?id=" + bean.getId() + "&type=" + type);
                                                    break;

                                            }
                                            dialog.dismiss();
                                        }
                                    })
                                    .setExpanded(true)
                                    .setGravity(Gravity.BOTTOM)
                                    .create();
                            dialogPlus.show();
                            sharePopUtil.dismiss();
                        }
                    }
                });
                sharePopUtil.show();
//
                return false;
            }
        });
    }

    /**
     * 判断是否收藏
     */
    private void ifCollected() {
        getTestApi().ifSolutionCollection(bean.getId(),1, SharePrefencesUtil.getFID(this),type)
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(ifCollectedObserver);
    }

    Observer<BaseBean> ifCollectedObserver=new Observer<BaseBean>() {
        @Override
        public void onCompleted() {
        }
        @Override
        public void onError(Throwable e) {
            Log.e("error", e.toString());
            hideLoading();
            showToast(R.string.neterror);
        }
        @Override
        public void onNext(BaseBean baseBean) {
            if(baseBean.getReturnInfo().equals(getResources().getString(R.string.nocollection))){
                addCollection();
            }else
            {
                showToast(R.string.solutioncollection);
            }
        }
    };
    /**
     * 添加收藏
     */
    private void addCollection() {
        getTestApi().addSolutioCollection(bean.getId(), "", 1, SharePrefencesUtil.getFID(this), type)
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(addCollectionObserver);
    }
    Observer<BaseBean> addCollectionObserver=new Observer<BaseBean>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            hideLoading();
            showToast(R.string.neterror);
            Log.e("error",e.toString());

        }

        @Override
        public void onNext(BaseBean baseBean) {
            Log.e("info",baseBean.getReturnInfo());
            showToast(baseBean.getReturnInfo());
        }
    };
}
